<template>



    <div class="app-container">

        <div class="total-layout">
            <el-row :gutter="20">
                <el-col :span="6">
                    <div class="total-frame">
                        <img :src="'/src/assets/icons/png/1.png'" class="total-icon">
                        <div class="total-title">今日订单总数</div>
                        <div class="total-value">{{this.orderCount}}</div>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="total-frame">
                        <img :src="'/src/assets/icons/png/2.png'" class="total-icon">
                        <div class="total-title">今日销售总额</div>
                        <div class="total-value">￥{{this.todayTotalSales}}</div>
                    </div>
                </el-col>

                <el-col :span="6">
                <div class="total-frame">
                    <img :src="'/src/assets/icons/png/3.png'" class="total-icon">
                     <div class="total-title">本周销售总额</div>
                     <div class="total-value">￥{{this.thisWeekTotalSales}}</div>
                </div>
                </el-col>

                <el-col :span="6">
                    <div class="total-frame">
                        <img :src="'/src/assets/icons/png/4.png'" class="total-icon">
                        <div class="total-title">本月销售总额</div>
                        <div class="total-value">￥{{this.thisMonthTotalSales}}</div>
                    </div>
                </el-col>
            </el-row>
        </div>


        <div class="statistics-layout">
            <div class="layout-title">订单统计</div>
            <el-row style="width: 100%;">
              <el-col :span="16">
                <div style="padding: 10px;border-left:1px solid #DCDFE6">
                  <el-date-picker
                      style="margin-left: 44%"
                      size="small"
                      v-model="dateRange"
                      :shortcuts="shortcuts"
                      type="datetimerange"
                      align="right"
                      unlink-panels
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      @change="handleDateChange"
                      :picker-options="pickerOptions"/>

                  <el-row style="width: 100%;">
                    <el-col :span="14">
                      <div id="main" style="width: 100% ; height: 500px"></div>
                    </el-col>
                    <el-col :span="5">
                      <div id="chartsDom" style="width: 600px ; height: 500px ; margin-left: 50px"></div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>

            <el-row>

            </el-row>

        </div>
    </div>
</template>

<script>
    import {str2Date} from '@/utils/date.js';
    import * as echarts from 'echarts';
    import {getDailyOrderCount , listOrder ,getTodayTotalSales,getThisMonthTotalSales,getThisWeekTotalSales,getTodayOrderCount} from "../../api/system/order.js";
    import {getGeoMap} from "@/api/system/getMap.js"



    export default {
        name: "orderStats",

        data(){
            return{
                chartDom : document.getElementById('main'),
                shortcuts : [
                {
                  text: '最近一周',
                  value: () => {
                    const end = new Date()
                    const start = new Date()
                    start.setDate(start.getDate() - 7)
                    return [start, end]
                  },
                },
                {
                  text: '最近一个月',
                  value: () => {
                    const end = new Date()
                    const start = new Date()
                    start.setMonth(start.getMonth() - 1)
                    return [start, end]
                  },
                },
                {
                  text: '最近三个月',
                  value: () => {
                    const end = new Date()
                    const start = new Date()
                    start.setMonth(start.getMonth() - 3)
                    return [start, end]
                  },
                },
              ],
              orderCountDate : [new Date(), new Date()],
              dateRange:[],
              detailDate:[],
              dailyOrderCount:[],
              todayTotalSales: 0, // 设置默认值为0
              thisWeekTotalSales: 0, // 设置默认值为0
              thisMonthTotalSales: 0, // 设置默认值为0
              orderCount: 0, // 设置默认值为0


            }
        },
        mounted() {



          this.setDefaultDateRange()

          this.statisticDailyOrders()

          this.initStatus()

          this.initLine()


        },
        methods:{

          initBar(){

            var chartDom = document.getElementById('chartsDom');
            var myChart = echarts.init(chartDom);
            var option;

            let dataAxis = this.detailDate

            let data = this.dailyOrderCount
            let yMax = 500;
            let dataShadow = [];
            for (let i = 0; i < data.length; i++) {
              dataShadow.push(yMax);
            }
            console.log('dataAxis',dataAxis)
            console.log('data',data)
            option = {
              title: {
                text: '销售订单统计',

              },
              xAxis: {
                data: dataAxis,
                axisLabel: {
                  inside: true,
                  color: '#fff'
                },
                axisTick: {
                  show: false
                },
                axisLine: {
                  show: false
                },
                z: 10
              },
              yAxis: {
                axisLine: {
                  show: false
                },
                axisTick: {
                  show: false
                },
                axisLabel: {
                  color: '#999'
                }
              },
              dataZoom: [
                {
                  type: 'inside'
                }
              ],
              series: [
                {
                  type: 'bar',
                  showBackground: true,
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#83bff6' },
                      { offset: 0.5, color: '#188df0' },
                      { offset: 1, color: '#188df0' }
                    ])
                  },
                  emphasis: {
                    itemStyle: {
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#2378f7' },
                        { offset: 0.7, color: '#2378f7' },
                        { offset: 1, color: '#83bff6' }
                      ])
                    }
                  },
                  data: data
                }
              ]
            };

            const zoomSize = 6;
            myChart.on('click', function (params) {
              console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
              myChart.dispatchAction({
                type: 'dataZoom',
                startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
                endValue:
                    dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
              });
            });

            option && myChart.setOption(option);


          },

          initStatus(){

            getTodayTotalSales().then(response => {
              this.todayTotalSales = response.data
              console.log('response',response)
              console.log('todayTotalSales',this.todayTotalSales)
            })
            getThisWeekTotalSales().then(response => {
              this.thisWeekTotalSales = response.data
              console.log('response',response)
              console.log('thisWeekTotalSales',this.thisWeekTotalSales)
            })
            getThisMonthTotalSales().then(response => {
              this.thisMonthTotalSales = response.data
              console.log('response',response)
              console.log('thisMonthTotalSales',this.thisMonthTotalSales)
            })
            getTodayOrderCount().then(response => {
              this.orderCount = response.data
              console.log('response',response)
              console.log('orderCount',this.orderCount)
            })

          },

          statisticDailyOrders() {
            // 获取所有订单
            listOrder({}).then(response => {
              const orders = response.rows;

              // 初始化每天的订单数量
              const dailyCounts = {};
              for (let key in this.detailDate) {
                if (this.detailDate.hasOwnProperty(key)) {
                  const date = this.detailDate[key];
                  dailyCounts[date] = 0; // 确保每个日期都初始化为0
                }
              }

              // 统计每天的订单数量
              orders.forEach(order => {
                const orderDate = new Date(order.orderDate).toISOString().slice(0, 10); // 只提取日期部分
                if (dailyCounts[orderDate] !== undefined) {
                  dailyCounts[orderDate]++;
                }
              });

              // 将结果存储到 dailyOrderCount 中，只保留订单数量
              this.dailyOrderCount = Object.keys(dailyCounts).sort().map(date => dailyCounts[date]);

              this.initLine()

              console.log(this.dailyOrderCount);
            }).catch(error => {
              console.error('Error fetching orders:', error);
            });
          },

         /* formatDateRange(startDate, endDate) {
            // 检查输入是否为有效的 Date 对象
            if (!(startDate instanceof Date && !isNaN(startDate)) || !(endDate instanceof Date && !isNaN(endDate))) {
              throw new Error('Invalid date provided');
            }

            // 定义一个用于格式化日期的函数
            function formatDate(date) {
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
              const day = String(date.getDate()).padStart(2, '0');
              const hours = String(date.getHours()).padStart(2, '0');
              const minutes = String(date.getMinutes()).padStart(2, '0');
              const seconds = String(date.getSeconds()).padStart(2, '0');

              return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }

            // 格式化起始和结束日期
            const formattedStartDate = formatDate(startDate);
            const formattedEndDate = formatDate(endDate);

            // 返回格式化的日期范围字符串
            return `${formattedStartDate},${formattedEndDate}`;
          },


          fetchDailyOrderCount(dateRange) {
            getDailyOrderCount(dateRange).then(response => {
              console.log(response.data)
            });
          },
*/

          setDefaultDateRange() {
            const today = new Date();
            const lastWeek = new Date(today);
            lastWeek.setDate(today.getDate() - 7);
            this.dateRange = [lastWeek, today];
            this.detailDate = this.generateDateRange(lastWeek, today);
          },

          handleDateChange(date) {

            console.log('date',date)
            if (date && date.length === 2) {
              const [startDate, endDate] = date;
             // this.fetchDailyOrderCount(this.formatDateRange(startDate, endDate));
              this.detailDate = this.generateDateRange(startDate, endDate);
              this.statisticDailyOrders()

              this.initLine();

            }
          },
          generateDateRange(startDate, endDate) {
            const dates = [];
            let currentDate = startDate;
            while (currentDate <= endDate) {
              dates.push(currentDate.toISOString().split('T')[0]);
              currentDate.setDate(currentDate.getDate() + 1);
            }
            return dates;
          },

          initLine() {
            var chartDom = document.getElementById('main');
            var myChart = echarts.init(chartDom);
            var option;

            option = {
              title: {
                text: '销售订单分布',

              },
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross'
                }
              },
              toolbox: {
                show: true,
                feature: {
                  saveAsImage: {
                    title: '保存为图片'
                  }
                }
              },
              xAxis: {
                type: 'category',
                boundaryGap: false,
                // 修改 X 轴数据为时间点或日期，这里假设是日期
                data: this.detailDate
              },
              yAxis: {
                type: 'value',
                name: '订单数量', // 添加 Y 轴名称
                axisLabel: {
                  formatter: '{value} 单' // 修改 Y 轴标签格式化器
                },
                axisPointer: {
                  snap: true
                }
              },
              visualMap: {
                show: false,
                dimension: 0,
                pieces: [
                  {
                    lte: 6,
                    color: 'green'
                  },
                  {
                    gt: 6,
                    lte: 8,
                    color: 'red'
                  },
                  {
                    gt: 8,
                    lte: 14,
                    color: 'green'
                  },
                  {
                    gt: 14,
                    lte: 17,
                    color: 'red'
                  },
                  {
                    gt: 17,
                    color: 'green'
                  }
                ]
              },
              series: [
                {
                  name: '订单数', // 修改系列名称
                  type: 'line',
                  smooth: true,
                  data: this.dailyOrderCount,
                  markArea: {
                    itemStyle: {
                      color: 'rgba(255, 173, 177, 0.4)'
                    },
                    data: [

                    ]
                  }
                }
              ]
            };

            option && myChart.setOption(option);

            this.initBar()
          }

        }
    }
</script>

<style scoped>
    .app-container {
        margin-top: 40px;
        margin-left: 120px;
        margin-right: 120px;
    }

    .address-layout {
    }

    .total-layout {
        margin-top: 20px;
    }

    .total-frame {
        border: 1px solid #DCDFE6;
        padding: 20px;
        height: 100px;
    }

    .total-icon {
        color: #409EFF;
        width: 60px;
        height: 60px;
    }

    .total-title {
        position: relative;
        font-size: 16px;
        color: #909399;
        left: 70px;
        top: -50px;
    }

    .total-value {
        position: relative;
        font-size: 18px;
        color: #606266;
        left: 70px;
        top: -40px;
    }

    .un-handle-layout {
        margin-top: 20px;
        border: 1px solid #DCDFE6;
    }

    .layout-title {
        color: #606266;
        padding: 15px 20px;
        background: #F2F6FC;
        font-weight: bold;
    }

    .un-handle-content {
        padding: 20px 40px;
    }

    .un-handle-item {
        border-bottom: 1px solid #EBEEF5;
        padding: 10px;
    }

    .overview-layout {
        margin-top: 20px;
    }

    .overview-item-value {
        font-size: 24px;
        text-align: center;
    }

    .overview-item-title {
        margin-top: 10px;
        text-align: center;
    }

    .out-border {
        border: 1px solid #DCDFE6;
    }

    .statistics-layout {
        margin-top: 20px;
        border: 1px solid #DCDFE6;
    }
    .mine-layout {
        position: absolute;
        right: 140px;
        top: 107px;
        width: 250px;
        height: 235px;
    }
    .address-content{
        padding: 20px;
        font-size: 18px
    }
</style>